import { ProTable } from '@ant-design/pro-components';
import {
  Button,
  Popconfirm,
  message,
  Tag,
  Upload,
  Image,
  Table,
  Space,
  Breadcrumb,
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useRequest } from 'umi';
import type { UploadProps } from 'antd';
import { UploadOutlined, FileSearchOutlined } from '@ant-design/icons';
import React, { useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import moment from 'moment';
import ImportExcel from '@/pages/LabManage/component/ImportExcel';

import { useBoolean } from 'ahooks';
import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
} from '@ant-design/pro-components';

export default () => {
  const formRef = useRef<ProFormInstance>();
  const editformRef = useRef<ProFormInstance>();
  const [selectRow, { toggle }] = useBoolean(false);

  const updateStatus = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/common/updateStatus',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  const props: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    accept: '.png,.jpeg,.jpg',
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        formRef.current?.setFieldsValue({ picPath: info.file.response.data });
        editformRef.current?.setFieldsValue({
          picPath: info.file.response.data,
        });
        message.success(`${info.file.name} 上传成功！`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败！`);
      }
    },
  };
  const props1: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        formRef.current?.setFieldsValue({ annexPath: info.file.response.data });
        editformRef.current?.setFieldsValue({
          annexPath: info.file.response.data,
        });
        message.success(`${info.file.name} 上传成功！`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  //获取国内外学术交流表
  const findAllVisit = useRequest((data = undefined) => {
    return {
      url: `http://10.1.40.84:9993/enterprise/findAllVisit`,
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });
  //新增国内外学术交流表
  const insertVisit = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/enterprise/insertVisit`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //删除国内外学术交流表
  const delVisit = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/enterprise/delVisit`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //编辑国内外学术交流表
  const updateVisit = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/enterprise/updateVisit`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  const confirm = (e: any) => {
    delVisit.run({ id: e.id }).then(() => {
      findAllVisit.run();
      message.success('删除成功');
    });
  };
  const cancel = (e: any) => {
    message.error('已取消');
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'seq',
      key: 'seq',
      width: 60,
      // copyable: true,
      hideInSearch: true,
    },
    {
      title: '交流年份',
      dataIndex: 'year',
      key: 'year',
      // width: 70,
      valueType: 'dateYear',
      hideInTable: true,
    },
    {
      title: '年份',
      dataIndex: 'year',
      key: 'year',
      hideInSearch: true,
      sorter: {
        compare: (a, b) => a.year - b.year,
      },
      valueType: 'dateYear',
      render: (text: any, record: any, index: any) => {
        return record?.year ? moment(record?.year + '').format('YYYY') : null;
      },
      width: 80,
    },
    {
      title: '来访人员',
      dataIndex: 'visitorName',
      key: 'visitorName',
      // copyable: true,
      // ellipsis: true,
    },
    {
      title: '交流主题',
      dataIndex: 'visitTopic',
      key: 'visitTopic',
      hideInSearch: true,
      width: 140,
      // ellipsis: true,
    },
    {
      title: '交流类型',
      dataIndex: 'visitType',
      key: 'visitType',
      hideInSearch: true,
    },
    {
      title: '来访时间',
      dataIndex: 'visitTime',
      key: 'visitTime',
      hideInSearch: true,
      render: (text: any) => <span>{moment(text).format('YYYY-MM-DD')}</span>,
    },
    {
      title: '报道链接',
      dataIndex: 'reportLink',
      key: 'reportLink',
      hideInSearch: true,
      render: (text: any, record: any) => {
        if (record.annexPath !== null) {
          return (
            <a
              onClick={() => {
                window.open(text);
              }}
            >
              查看链接
            </a>
          );
        } else {
          return <span>暂无链接</span>;
        }
      },
    },
    {
      title: '材料',
      dataIndex: 'annexPath',
      key: 'annexPath',
      hideInSearch: true,
      render: (text: any, record: any) => {
        if (record.annexPath !== null) {
          return (
            <a
              onClick={() => {
                window.open(text);
              }}
            >
              下载
            </a>
          );
        } else {
          return <span>暂无材料</span>;
        }
      },
    },
    {
      title: '现场照片',
      dataIndex: 'picPath',
      key: 'picPath',
      hideInSearch: true,
      width: '140px',
      render: (text: any, record: any) => {
        if (record.picPath !== null) {
          return <Image src={text} width={130}></Image>;
        } else {
          return null;
        }
      },
    },
    // {
    //   title: '审查状态',
    //   dataIndex: 'isPass',
    //   key: 'isPass',
    //   hideInSearch: true,
    // },
    {
      title: '审核情况',
      key: 'isPass',
      dataIndex: 'isPass',
      hideInSearch: true,
      width: '8%',
      render: (text: any, record: any, index: any) => {
        switch (text) {
          case 0:
            return '未通过(待上传文件)';
          case 1:
            return '未审核';
          case 2:
            return '审核通过';
          case 3:
            return '审核失败';
        }
      },
    },

    {
      title: '操作',
      key: 'option',
      // width: 120,
      valueType: 'option',
      render: (text: any, record: any) => [
        <ModalForm
          title="编辑学术交流"
          trigger={<a key="1">编辑</a>}
          autoFocusFirstInput
          modalProps={{
            onCancel: () => console.log('run'),
          }}
          submitTimeout={2000}
          onFinish={async (values) => {
            console.log(values);
            updateVisit.run(values).then(() => {
              message.info('编辑成功！');
              findAllVisit.run();
            });
            return true;
          }}
          initialValues={{ ...record, year: record.year + '' }}
          key="1"
          formRef={editformRef}
        >
          <ProForm.Group>
            <ProFormText name="id" hidden />
            <ProFormDatePicker.Year name="year" label="年份" />
            <ProFormText width="md" name="visitorName" label="来访人员" />
            <ProFormText width="sm" name="visitTopic" label="交流主题" />
            <ProFormSelect
              width="sm"
              options={[
                {
                  value: '国内专家来室交流',
                  label: '国内专家来室交流',
                },
                {
                  value: '国外专家来室交流',
                  label: '国外专家来室交流',
                },
                {
                  value: '本室人员到国内其他单位交流',
                  label: '本室人员到国内其他单位交流',
                },
                {
                  value: '本室人员到国外交流',
                  label: '本室人员到国外交流',
                },
                {
                  value: '参加国内会议',
                  label: '参加国内会议',
                },
                {
                  value: '参加国外会议',
                  label: '参加国外会议',
                },
              ]}
              name="visitType"
              label="交流类型"
            />
            <ProFormDatePicker name="visitTime" label="来访时间" />
            <ProFormText width="xl" name="reportLink" label="报道链接" />
            <ProFormText width="sm" name="picPath" hidden />
            <ProFormText width="sm" name="annexPath" hidden />
          </ProForm.Group>

          <ProForm.Group>
            <Upload {...props}>
              <Button
                icon={<UploadOutlined />}
                type="link"
                style={{ marginTop: 12 }}
              >
                上传照片
              </Button>
            </Upload>
            <Upload {...props1}>
              <Button
                icon={<UploadOutlined />}
                type="link"
                style={{ marginTop: 12 }}
              >
                上传材料（上传会议照片，以会议名称命名）
              </Button>
            </Upload>
          </ProForm.Group>
        </ModalForm>,
        <Popconfirm
          key={'2'}
          title="确定删除吗？"
          onConfirm={() => confirm(record)}
          onCancel={() => cancel}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];
  const Refresh = () => {
    findAllVisit.run();
  };

  return (
    <PageContainer
      header={{
        title: null,
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>合作交流</Breadcrumb.Item>
            <Breadcrumb.Item>国内外学术交流</Breadcrumb.Item>
          </Breadcrumb>
        ),
        extra: [
          // <ImportExcel
          //   key="1"
          //   tableName={'VISIT_ENTERPRISE'}
          //   Refresh={Refresh}
          // />,
          // <Button
          //   key="2"
          //   type="primary"
          //   onClick={() => {
          //     window.open(
          //       'http://10.1.40.84:9993/file/model/VISIT_ENTERPRISE_模板.xlsx ',
          //     );
          //   }}
          // >
          //   下载模版
          // </Button>,
        ],
      }}
    >
      <ProTable
        columns={columns}
        dataSource={findAllVisit?.data}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
        }}
        onSubmit={(e: any) => {
          findAllVisit.run(e);
        }}
        onReset={() => {
          findAllVisit.run();
        }}
        search={{
          labelWidth: 'auto',
        }}
        loading={findAllVisit.loading}
        dateFormatter="string"
        headerTitle="国内外学术交流列表"
        options={false}
        toolBarRender={() => [
          <div>
            {tabKey === '管理员视角' || tabKey === '子方向视角' ? (
              <Button
                type="primary"
                icon={<FileSearchOutlined />}
                onClick={() => {
                  toggle();
                }}
              >
                批量审核
              </Button>
            ) : null}
          </div>,
          <ModalForm
            title="新增国内外学术交流"
            trigger={
              <Button key="primary" type="primary">
                新增国内外学术交流
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log('run'),
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              console.log(values);
              insertVisit.run(values).then(() => {
                findAllVisit.run();
                message.info('添加成功！');
              });
              return true;
            }}
            key="1"
            formRef={formRef}
          >
            <ProForm.Group>
              <ProFormDatePicker.Year name="year" label="年份" />
              <ProFormText width="md" name="visitorName" label="来访人员" />
              <ProFormText width="sm" name="visitTopic" label="交流主题" />
              <ProFormSelect
                width="sm"
                options={[
                  {
                    value: '国内专家来室交流',
                    label: '国内专家来室交流',
                  },
                  {
                    value: '国外专家来室交流',
                    label: '国外专家来室交流',
                  },
                  {
                    value: '本室人员到国内其他单位交流',
                    label: '本室人员到国内其他单位交流',
                  },
                  {
                    value: '本室人员到国外交流',
                    label: '本室人员到国外交流',
                  },
                  {
                    value: '参加国内会议',
                    label: '参加国内会议',
                  },
                  {
                    value: '参加国外会议',
                    label: '参加国外会议',
                  },
                ]}
                name="visitType"
                label="交流类型"
              />
              <ProFormDatePicker name="visitTime" label="来访时间" />
              <ProFormText width="xl" name="reportLink" label="报道链接" />
              <ProFormText width="sm" name="picPath" hidden />
              <ProFormText width="sm" name="annexPath" hidden />
            </ProForm.Group>

            <ProForm.Group>
              <Upload {...props}>
                <Button
                  icon={<UploadOutlined />}
                  type="link"
                  style={{ marginTop: 12 }}
                >
                  上传照片
                </Button>
              </Upload>
              <Upload {...props1}>
                <Button
                  icon={<UploadOutlined />}
                  type="link"
                  style={{ marginTop: 12 }}
                >
                  上传材料（上传会议照片，以会议名称命名）
                </Button>
              </Upload>
            </ProForm.Group>
          </ModalForm>,
          <ImportExcel
            key="1"
            tableName={'VISIT_ENTERPRISE'}
            Refresh={Refresh}
          />,
          <Button
            key="2"
            type="primary"
            onClick={() => {
              window.open(
                'http://10.1.40.84:9993/file/model/VISIT_ENTERPRISE_模板.xlsx ',
              );
            }}
          >
            下载模版
          </Button>,
        ]}
        rowSelection={
          selectRow
            ? {
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
              }
            : false
        }
        tableAlertOptionRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={16}>
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'VISIT_ENTERPRISE',
                    ids: selectedRowKeys,
                    status: 2, //审核通过
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    findAllVisit.run();
                  });
              }}
            >
              审核通过
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'VISIT_ENTERPRISE',
                    ids: selectedRowKeys,
                    status: 3, //拒绝
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    findAllVisit.run();
                  });
              }}
            >
              拒绝
            </a>
          </Space>
        )}
      />
    </PageContainer>
  );
};
